package com.jms.tomcat.handler;

import com.jms.tomcat.http.JmsRequest;
import com.jms.tomcat.http.JmsResponse;
import com.jms.tomcat.http.JmsServletError;
import com.jms.tomcat.core.JmsServletContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.Socket;

/**
 * 每一个socket连接的处理器
 */
public class RequestHandler implements Runnable {

    private static final Logger logger = LogManager.getLogger(RequestHandler.class);
    private final Socket socket;
    private final JmsServletContext servletContext;
    public RequestHandler(Socket socket, JmsServletContext servletContext) {
        this.socket = socket;
        this.servletContext = servletContext;
    }

    @Override
    public void run() {
        JmsRequest request;
        JmsResponse response = null;

        try {
            response = new JmsResponse(socket.getOutputStream(), servletContext);
            request = new JmsRequest(socket.getInputStream(), servletContext);
            servletContext.process(request, response);
        } catch (Exception e) {
            if (response != null) {
                if (JmsServletError.NOT_FOUND.equals(e.getMessage())) {
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                } else if (JmsServletError.BAD_REQUEST.equals(e.getMessage())) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    logger.warn(e.getMessage());
                } else if (JmsServletError.METHOD_NOT_ALLOWED.equals(e.getMessage())) {
                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                    logger.warn(e.getMessage());
                } else {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    logger.error(e.getMessage(), e);
                }
            } else {
                logger.error(e.getMessage(), e);
            }
        } finally {
            if (response != null) {
                try {
                    response.flushBuffer();
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
